import React, { useEffect, useState } from 'react';

const Index = () => {
    const [list, setList] = useState([]);
    const [msg, setMsg] = useState("");
    const getLocal = ()=>{
       const  list = JSON.parse(localStorage.getItem("hooks"))||[];
        setList(()=>{
            return [...list]
        })
    }
    useEffect(()=>{
        getLocal()
    },[])
    const handleChange = (e) => {
        setMsg(e.target.value)
    }
    const toDo = (e) => {
        if (e.keyCode == 13) {
            var obj = {
                msg: e.target.value,
                checked: false,
                id: Math.random(),
            };
            var s = list.findIndex((item) => item.msg === obj.msg);
            if (s === -1 && obj.msg != '') {
                list.unshift(obj);
            }
            setMsg("")
            local();
        }
    }
    const toChange = (index) => {
        list[index].checked = !list[index].checked;
        local();
        setList(()=>{
            return [...list]
        })
    }
    const toDelete = (val) => {
        list.splice(val, 1);
        local();
        setList(()=>{
            return [...list]
        })
    }
    const local = () => {
        localStorage.setItem("hooks", JSON.stringify(list))
    }



    const ListItem = list.map((item, index) => {
        if (item.checked === false) {
            return (
                <div key={item.id}>
                    <input type="checkbox" name="" id="" checked={item.checked} onChange={() => toChange(index)} />
                    {item.msg}
                    <button onClick={() => toDelete(index)}>删除</button>
                </div>
            )
        }
    })
    const DoneItem = list.map((item, index) => {
        if (item.checked === true) {
            return (
                <div key={item.id}>
                    <input type="checkbox" name="" id="" checked={item.checked} onChange={() => toChange(index)} />
                    {item.msg}
                    <button onClick={() => toDelete(index)}>删除</button>
                </div>
            )
        }
    })
    return (
        <div>
            <h1>TodoList</h1>
            <input type="text" onChange={handleChange} value={msg} onKeyUp={toDo} />
            <h2>进行中</h2>
            {ListItem}
            <h2>已完成</h2>
            {DoneItem}
        </div>
    );
}

export default Index;
